import router from './index';
import store from '../store';
import NProgress from 'nprogress'; // Progress 进度条
import 'nprogress/nprogress.css';// Progress 进度条样式
import { Message } from 'element-ui';
import { getToken } from '@/utils/auth'; // 验权
import { getList, getReceiveList, setListRead } from '@/api/todo';
import { pageChangeEV } from '@/utils/requestEV/ev';
import { isNewVersion } from '@/utils/versionCheck';

const whiteList = ['/login', '/404']; // 不重定向白名单

router.beforeEach((to, from, next) => {
  // 前端版本更新检查
  isNewVersion();
  if (to.meta.title) {
    document.title = to.meta.title;
    if (to.query.createNew) {
      document.title = document.title.replace('编辑', '新建');
    }
  }
  NProgress.start();
  // if (to.path === '/homePage/index') {
  //   const a = { 'name': 'contractDetail', 'query': { 'processId': 'ODgzMDgyOTczNzc4OTU=' }, 'params': { 'id': 'NDc4MjkxMzcyMzk3ODk=' }};
  //   next(a);
  //   return;
  // }
  if (getToken()) {
    if (to.path === '/login' || to.path === '/') {
      next({ name: 'Index' });
      NProgress.done(); // if current page is index will not trigger	afterEach hook, so manually handle it
    } else {
      if (to.path === '/system/setting') {
        !store.getters.collectOptions && store.dispatch('GetCollectOptions');
      }
      // 获取快捷筛选条件
      store.dispatch('getFilterConfig');
      if (to.query.fromDingDing === '1' && to.query.workFlowReceiveId && to.query.workFlowReceiveId !== 'null') {
        setListRead(Number(to.query.workFlowReceiveId)); // 从钉钉跳转，将该条未读标为已读
      }
      const params = {
        page: 1,
        perPage: 20,
        isExpedited: 0,
        tabStatus: 0
      };
      getList(params).then((res) => {
        if (res.code === 200) {
          const params1 = {
            page: 1,
            perPage: 20,
            tabStatus: 3,
            onlyUnread: 1
          };
          getReceiveList(params1).then((result) => {
            store.commit('SETNOTICENUM', { total: res.data.total, unTotal: result.data.total });
          });
        }
      });
      // if (store.getters.fieldList.length === 0) {
      //   store.dispatch('GetFieldList');
      // }
      if (store.getters.roles.length === 0) {
        store.dispatch('GetInfo').then(res => { // 拉取用户信息
          next(to.fullPath);
        }).catch((err) => {
          store.dispatch('FedLogOut').then(() => {
            Message.error(err || '验证错误，请重新登录');
            // next(`/login?redirect=${to.path}`); // 否则全部重定向到登录页
            next(`/login`);
          });
        });
      } else {
        // 这一步主要是为了清除 ？ 后面，# 前面的 location.search 参数，避免url过长
        if (location && location.search) {
          // 如果有跳转参数，则跳转完后再清除 location.search
          const query = new URLSearchParams(location.search || '?');
          let redirect = query.get('redirect');
          if (redirect && redirect !== '' && redirect !== 'null') {
            for (const [key, value] of query.entries()) {
              if (key !== 'redirect' && value) {
                redirect += `${redirect.indexOf('?') < 0 ? '?' : '&'}${key}=${value}`;
              }
            }
            history.replaceState({}, '', '/');
            console.log('Index:', redirect);
            let path = decodeURIComponent(redirect);
            // 后端约定将字符‘@-5’统一转换成空格
            path = path.replace(/@-5/g, ' ');
            next({ path: path });
            return;
          }
          history.replaceState({}, '', '/');
        }

        // 统计
        const reportValue = {
          page: to.meta && to.meta.title ? to.meta.title : to.name, userId: store.getters.id || ''
        };
        if (reportValue.page && process.env.NODE_ENV !== 'development') pageChangeEV(reportValue);
        // if (window.LA && window.LA.track) {
        //   window.LA.track('Go_To_Page', reportValue);
        // }

        next(); // 真正成功跳转
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      // const redirectName = ['contractDetail', 'supplierDetail', 'orderDetail'];
      const redirectName = ['overview', 'login', 'user'];
      const { name, query, params } = to;
      if (!redirectName.includes(name) && to.path !== '/index' && to.path !== '/') {
        const obj = JSON.parse(JSON.stringify({
          name,
          query,
          params
        }));
        const reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g');
        if (obj.query && typeof obj.query === 'object') {
          for (const key of Object.keys(obj.query)) {
            if (obj.query[key] && reg.test(obj.query[key])) {
              obj.query[key] = encodeURI(obj.query[key]);
            }
          }
        }
        const value = encodeURIComponent(JSON.stringify(obj));
        next(`/login?loginredirect=${value}`);
        //   window.location.reload();
      } else {
        next('/login');
      }
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done(); // 结束Progress
  const list = document.getElementsByClassName('el-tooltip__popper');
  if (list && list.length > 0) {
    list[list.length - 1].style.display = 'none';
  }
  // freshVersion();
});

// function freshVersion() { // 发版本后更新页面
//   const { APP_BUILD_VERSION } = process.env;
//   const localVersion = localStorage.getItem('VERSION');
//   console.log(APP_BUILD_VERSION, localVersion);
//   if (APP_BUILD_VERSION && localVersion && localVersion !== APP_BUILD_VERSION) {
//     setTimeout(() => {
//       location.reload(true);
//       console.log('刷新页面');
//     }, 300);
//   }
//   if (APP_BUILD_VERSION) localStorage.setItem('VERSION', APP_BUILD_VERSION);
// }
